//****************************************************************
//* Copyright (c) 2008 Ford Motor Company. All Rights Reserved.
//*
//* $$Workfile:   CostStructureNewAction.java  $$
//* $$Revision:   1.1  $$
//* $$Author:   JLOPE262  $$
//* $$Date:   Nov 21 2008 14:26:34  $$
//*
//*****************************************************************
package ar.com.ford.it.fullEconomics.view.action;

import java.util.Collection;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.CostStructureFacade;
import ar.com.ford.it.fullEconomics.facade.SupplierFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc02Coststvers;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.view.form.CostStructureNewForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;
import com.ford.it.persistence.PersistenceException;

public class CostStructureNewAction extends AbstractBaseAction {

    private Collection<OptionCombo> getComboTypesCostStructure(
                                                               HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("S", resources
                .getMessage("costStructure.new.label.supplier")));
        list.add(new OptionCombo("C", resources.getMessage("commodity.label")));
        list.add(new OptionCombo("P", resources.getMessage("part.label")));

        return list;
    }

    /**
     * Setea el error que indica que la Cost Structure no puede ser aprobada
     * 
     * @param request
     */
    private void setErrorCostStructureCannotBeApproved(
                                                       HttpServletRequest request) {
        ActionMessages am = new ActionMessages();

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "costStructure.new.error.approve.sameUser"));
        saveErrors(request, am);
    }

    /**
     * Setea el error que informa que la estructura de costos no puede ser
     * aprobada dado que alguno de sus items no esta aprobado.
     * 
     * @param request
     */
    private void setErrorNotAllSubCostStrItemsAreApproved(
                                                          HttpServletRequest request) {
        ActionMessages am = new ActionMessages();

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "costStructure.find.error.approve.itemsNotApproved"));
        saveErrors(request, am);
    }

    /**
     * Setea las colecciones, resetea el formulario y demas tareas de
     * inicializacion
     * 
     * @param form
     * @param request
     * @param user
     * @throws FullEconomicsException
     */
    private void setInitParameters(CostStructureNewForm form,
                                   HttpServletRequest request,
                                   FullEconomicsWslxUser user)
            throws FullEconomicsException {
        SupplierFacade supplierFacade = (SupplierFacade) FacadeProvider
                .getFacade(request, SupplierFacade.class);
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);

        form.resetForm();
        form.setSupplierTypeCol(supplierFacade.getComboSupplierType());
        request.getSession().setAttribute("supplierTypeCol",
                form.getSupplierTypeCol());
        form.setPartClassesCol(commodityFacade.getPartClases());
        request.getSession().setAttribute("partClassesCol",
                form.getPartClassesCol());
        form.setCommoditiesCol(commodityFacade.findCommodities("", "", user
                .getTeesg01Plant()));
        request.getSession().setAttribute("commoditiesCol",
                form.getCommoditiesCol());
        form.setTypesCostStructureCol(this.getComboTypesCostStructure(request));
        request.getSession().setAttribute("typesCostStructureCol",
                form.getTypesCostStructureCol());
    }

    /**
     * Chequea si existe el supplier y en caso de que no exista setea el mensaje
     * de error
     * 
     * @param facade
     * @param plant
     * @param supplier
     * @return
     * @throws FullEconomicsException
     * @throws PersistenceException
     */
    private boolean supplierExists(SupplierFacade facade, Teesg01Plant plant,
                                   Teess01Supplier supplier,
                                   HttpServletRequest request)
            throws FullEconomicsException {
        boolean ret = true;
        ActionMessages am = null;
        MessageResources messageResources = null;

        supplier.setEess01PlantCodeC(plant);
        supplier = facade.getSupplierByPk(supplier);

        if (supplier == null) {
            am = new ActionMessages();
            messageResources = (MessageResources) getResources(request);
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "error.notExists.m", messageResources
                            .getMessage("supplier.label.supplier")));
            saveErrors(request, am);
            ret = false;
        }

        return ret;
    }

    /**
     * Chequea si la parte existe
     * 
     * @param facade
     * @param plant
     * @param partClass
     * @param partPrefix
     * @param partBase
     * @param partSuffix
     * @param request
     * @return
     * @throws FullEconomicsException
     */
    private boolean partExists(CommodityFacade facade, Teesg01Plant plant,
                               Teesp01Part part, HttpServletRequest request)
            throws FullEconomicsException {
        boolean ret = true;
        ActionMessages am = null;
        MessageResources messageResources = null;

        part.setEesp01PlantCodeC(plant);
        part = facade.findPartByPk(part);

        if (part == null) {
            am = new ActionMessages();
            messageResources = (MessageResources) getResources(request);
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "error.notExists.f", messageResources
                            .getMessage("part.label")));
            saveErrors(request, am);
            ret = false;
        }

        return ret;
    }

    /**
     * Chequea si existe la pieza. Si no existe devuelve false y ademas setea el
     * mensaje de error.
     * 
     * @param facade
     * @param plant
     * @param partClass
     * @param partPrefix
     * @param partBase
     * @param partSuffix
     * @param request
     * @return
     * @throws FullEconomicsException
     */
    private boolean supplyExists(CommodityFacade facade, Teesg01Plant plant,
                                 Teesp01Part part, Teess01Supplier supplier,
                                 HttpServletRequest request)
            throws FullEconomicsException {
        boolean ret = true;
        Collection<Teesp01Part> parts = null;
        ActionMessages am = null;

        part.setEesp01PlantCodeC(plant);
        parts = facade.findParts(part, null, null, supplier
                .getEess01SupplierClassCodeC(), supplier
                .getEess01SupplierCodeC());

        if (parts == null || parts.isEmpty()) {
            am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "costStructure.new.error.suppy"));
            saveErrors(request, am);
            ret = false;
        }

        return ret;
    }

    /**
     * 
     */
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {
        CostStructureNewForm form = (CostStructureNewForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();

        try {
            this.setInitParameters(form, request, user);
            form.setVersion("1");
            form.setComeFrom("menu");
            form.setBlockAppliesTo("false");
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward saveCostStructure(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {
        CostStructureNewForm form = (CostStructureNewForm) actionForm;
        CostStructureFacade facade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        SupplierFacade supplierFacade = (SupplierFacade) FacadeProvider
                .getFacade(request, SupplierFacade.class);
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        Teesp01Part part = null;
        Teess01Supplier supplier = null;
        String forward = "success";

        try {
            supplier = form.getSupplier();
            part = form.getPart();

            if (this.supplierExists(supplierFacade, user.getTeesg01Plant(),
                    supplier, request)) {
                if (form.getCostStructureTypeSel().equals("P")) {
                    if (this.partExists(commodityFacade,
                            user.getTeesg01Plant(), part, request)) {
                        if (this.supplyExists(commodityFacade, user
                                .getTeesg01Plant(), part, supplier, request)) {
                            if ("menu".equals(form.getComeFrom())) {
                                facade.createCostStructure(user, form
                                        .getCostStructureCreateStruct());
                            } else if ("newVersion".equals(form.getComeFrom())) {
                                facade.createNewCostStructureVersion(user, form
                                        .getCostStrForNewVersion());
                            } else if ("copyTo".equals(form.getComeFrom())) {
                                facade.copyCostStructureVersion(user, form
                                        .getCostStrVersion(), form
                                        .getCostStructureCreateStruct());
                            }
                        } else {
                            forward = "noSuccess";
                        }
                    } else {
                        forward = "noSuccess";
                    }
                } else {
                    if ("menu".equals(form.getComeFrom())) {
                        facade.createCostStructure(user, form
                                .getCostStructureCreateStruct());
                    } else if ("newVersion".equals(form.getComeFrom())) {
                        facade.createNewCostStructureVersion(user, form
                                .getCostStrForNewVersion());
                    } else if ("copyTo".equals(form.getComeFrom())) {
                        facade.copyCostStructureVersion(user, form
                                .getCostStrVersion(), form
                                .getCostStructureCreateStruct());
                    }
                }
            } else {
                forward = "noSuccess";
            }
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward(forward);
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward updateCostStructure(FordActionMapping mapping,
                                             ActionForm actionForm,
                                             HttpServletRequest request,
                                             HttpServletResponse response,
                                             WebSession webSession,
                                             ActionMessages msgs,
                                             ActionMessages warns,
                                             ActionMessages errorMsgs) {
        CostStructureNewForm form = (CostStructureNewForm) actionForm;
        CostStructureFacade facade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        SupplierFacade supplierFacade = (SupplierFacade) FacadeProvider
                .getFacade(request, SupplierFacade.class);
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        Teesp01Part part = null;
        Teess01Supplier supplier = null;
        String forward = "success";

        try {
            supplier = form.getSupplier();
            part = form.getPart();
            if (this.supplierExists(supplierFacade, user.getTeesg01Plant(),
                    supplier, request)) {
                if (form.getCostStructureTypeSel().equals("P")) {
                    if (this.partExists(commodityFacade,
                            user.getTeesg01Plant(), part, request)) {
                        if (this.supplyExists(commodityFacade, user
                                .getTeesg01Plant(), part, supplier, request)) {
                            facade.updateCostStructureVersion(user, form
                                    .getCostStrVersionForUpdate());
                        }
                    }
                } else {
                    facade.updateCostStructureVersion(user, form
                            .getCostStrVersionForUpdate());
                }
            }
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward(forward);
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward detailsCostStructure(FordActionMapping mapping,
                                              ActionForm actionForm,
                                              HttpServletRequest request,
                                              HttpServletResponse response,
                                              WebSession webSession,
                                              ActionMessages msgs,
                                              ActionMessages warns,
                                              ActionMessages errorMsgs) {
        CostStructureNewForm form = (CostStructureNewForm) actionForm;
        CostStructureFacade facade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        SupplierFacade supplierFacade = (SupplierFacade) FacadeProvider
                .getFacade(request, SupplierFacade.class);
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        Teesp01Part part = null;
        Teess01Supplier supplier = null;
        Teesc02Coststvers ret = null;
        String forward = "success";

        try {
            supplier = form.getSupplier();
            part = form.getPart();
            if (this.supplierExists(supplierFacade, user.getTeesg01Plant(),
                    supplier, request)) {
                if (form.getCostStructureTypeSel().equals("P")) {
                    if (this.partExists(commodityFacade,
                            user.getTeesg01Plant(), part, request)) {
                        if (this.supplyExists(commodityFacade, user
                                .getTeesg01Plant(), part, supplier, request)) {
                            if ("menu".equals(form.getComeFrom())) {
                                ret = facade.createCostStructure(user, form
                                        .getCostStructureCreateStruct());
                            } else if ("newVersion".equals(form.getComeFrom())) {
                                ret = facade.createNewCostStructureVersion(
                                        user, form.getCostStrForNewVersion());
                            } else if ("copyTo".equals(form.getComeFrom())) {
                                ret = facade
                                        .copyCostStructureVersion(user, form
                                                .getCostStrVersion(), form
                                                .getCostStructureCreateStruct());
                            } else if (("header").equals(form.getComeFrom())) {
                                ret = form.getCostStrVersion();
                            }
                        } else {
                            forward = "noSuccess";
                        }
                    } else {
                        forward = "noSuccess";
                    }
                } else {
                    if ("menu".equals(form.getComeFrom())) {
                        ret = facade.createCostStructure(user, form
                                .getCostStructureCreateStruct());
                    } else if ("newVersion".equals(form.getComeFrom())) {
                        ret = facade.createNewCostStructureVersion(user, form
                                .getCostStrForNewVersion());
                    } else if ("copyTo".equals(form.getComeFrom())) {
                        ret = facade.copyCostStructureVersion(user, form
                                .getCostStrVersion(), form
                                .getCostStructureCreateStruct());
                    } else if (("header").equals(form.getComeFrom())) {
                        ret = form.getCostStrVersion();
                    }
                }
            }
            request.setAttribute("costStrVersionSelected", ret);
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward(forward);
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward proposeCostStructure(FordActionMapping mapping,
                                              ActionForm actionForm,
                                              HttpServletRequest request,
                                              HttpServletResponse response,
                                              WebSession webSession,
                                              ActionMessages msgs,
                                              ActionMessages warns,
                                              ActionMessages errorMsgs) {
        CostStructureNewForm form = (CostStructureNewForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CostStructureFacade facade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);

        if (facade.costStructureCanBeProposed(form.getCostStrVersion())) {
            try {
                facade.proposeCostStructure(form.getCostStrVersion(), user);
                form.setDetails();
            } catch (FullEconomicsException e) {
                ActionMessages am = new ActionMessages();
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource()));
                saveErrors(request, am);
            }
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward approveCostStructure(FordActionMapping mapping,
                                              ActionForm actionForm,
                                              HttpServletRequest request,
                                              HttpServletResponse response,
                                              WebSession webSession,
                                              ActionMessages msgs,
                                              ActionMessages warns,
                                              ActionMessages errorMsgs) {
        CostStructureNewForm form = (CostStructureNewForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CostStructureFacade facade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);

        try {
            if (facade.costStructureCanBeApproved(form.getCostStrVersion(),
                    user)) {
                if (facade.checkIfallItemsAreApproved(form.getCostStrVersion())) {
                    facade.approveCostStructure(form.getCostStrVersion(), user);
                    form.setDetails();
                } else {
                    this.setErrorNotAllSubCostStrItemsAreApproved(request);
                }
            } else {
                this.setErrorCostStructureCannotBeApproved(request);
            }
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward newCostStructureVersion(FordActionMapping mapping,
                                                 ActionForm actionForm,
                                                 HttpServletRequest request,
                                                 HttpServletResponse response,
                                                 WebSession webSession,
                                                 ActionMessages msgs,
                                                 ActionMessages warns,
                                                 ActionMessages errorMsgs) {
        CostStructureNewForm form = (CostStructureNewForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        Teesc02Coststvers costStrVersion = null;

        try {
            this.setInitParameters(form, request, user);
            costStrVersion = (Teesc02Coststvers) request
                    .getAttribute("costStrVersionSelected");
            form.setCostStrVersion(costStrVersion);
            form.setBlockAppliesTo("true");
            form.setComeFrom("newVersion");
            form.setDetails();
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward costStructureVersionCopyTo(
                                                    FordActionMapping mapping,
                                                    ActionForm actionForm,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response,
                                                    WebSession webSession,
                                                    ActionMessages msgs,
                                                    ActionMessages warns,
                                                    ActionMessages errorMsgs) {
        CostStructureNewForm form = (CostStructureNewForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        Teesc02Coststvers costStrVersion = null;

        try {
            this.setInitParameters(form, request, user);
            costStrVersion = (Teesc02Coststvers) request
                    .getAttribute("costStrVersionSelected");
            form.setCostStrVersion(costStrVersion);
            form.setBlockAppliesTo("false");
            form.setComeFrom("copyTo");
            form.setDetails();
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward costStructureVersionHeader(
                                                    FordActionMapping mapping,
                                                    ActionForm actionForm,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response,
                                                    WebSession webSession,
                                                    ActionMessages msgs,
                                                    ActionMessages warns,
                                                    ActionMessages errorMsgs) {
        CostStructureNewForm form = (CostStructureNewForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        Teesc02Coststvers costStrVersion = null;

        try {
            this.setInitParameters(form, request, user);
            costStrVersion = (Teesc02Coststvers) request
                    .getAttribute("costStrVersionSelected");
            form.setCostStrVersion(costStrVersion);
            form.setBlockAppliesTo("true");
            form.setComeFrom("header");
            form.setDetails();
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

}
